package com.example.demo.service.Impl;


import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.example.demo.mapper.UserMapper;
import com.example.demo.pojo.User;
import com.example.demo.service.IUserService;
import com.example.demo.vo.UserVo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;
import javax.mail.*;
import javax.mail.internet.InternetAddress;
import javax.mail.internet.MimeMessage;
import java.time.Duration;
import java.util.Properties;
import java.util.UUID;
import java.util.concurrent.ThreadLocalRandom;

/**
 * @author HL
 */
@Service
public class UserServiceImpl extends ServiceImpl<UserMapper, User> implements IUserService {
    @Autowired UserMapper userMapper;
    @Autowired RedisTemplate redisTemplate;

    @Override
    public UserVo register(String name, String password, String email, Integer check) {
        if(redisTemplate.opsForValue().get(email) == null || String.valueOf(check).compareTo((String)redisTemplate.opsForValue().get(email)) != 0) {
            return new UserVo(new User("10004", null));
        }
        if(userMapper.selectUserByEmail(email) != null) {
            return new UserVo(new User("10005", null));
        }
        redisTemplate.delete(email);
        String account = String.valueOf((long) ((Math.random() * 9.0 + 1) * (Math.pow(10, 9))));
        while(userMapper.selectUserByAccount(account) != null){ account = String.valueOf((long) ((Math.random() * 9.0 + 1) * (Math.pow(10, 9))));}
        User user1 = new User(account, name, password, email, "https://www.keaitupian.cn/cjpic/frombd/0/253/3393306820/581673443.jpg");
        userMapper.addUser(user1);
        user1 = userMapper.selectUserByAccount(account);
        redisTemplate.opsForValue().set(account,  user1);
        redisTemplate.expire(user1.getAccount(), Duration.ofDays(3));
        return new UserVo(user1);
    }

    @Override
    public UserVo logonByAccount(String account, String password) {
        User user1 = (User) redisTemplate.opsForValue().get(account);
        if(user1 != null) {
            //System.out.println(user1);  //用于验证是否从redis内获取
            if(user1.getPassword().compareTo(password) == 0) {
                redisTemplate.expire(user1.getAccount(), Duration.ofDays(3));
                String textNew = UUID.randomUUID().toString();
                UserVo user = new UserVo(user1);
                user.setCiphertext(textNew);
                redisTemplate.opsForValue().set(textNew, user);
                redisTemplate.expire(textNew, Duration.ofDays(3));
                return user;
            }
            else {
                return new UserVo(new User("10003", null));
            }
        }
        user1 = userMapper.selectUserByAccount(account);
        if(user1 == null) {
            return new UserVo(new User("10004", null));
        }
        if(user1.getPassword().compareTo(password) == 0){
            redisTemplate.opsForValue().set(account, user1);
            redisTemplate.expire(user1.getAccount(), Duration.ofDays(3));
            String textNew = UUID.randomUUID().toString();
            UserVo user = new UserVo(user1);
            user.setCiphertext(textNew);
            redisTemplate.opsForValue().set(textNew, user);
            redisTemplate.expire(textNew, Duration.ofDays(3));
            return user;
        }
        else {
            return new UserVo(new User("10003", null));
        }
    }

    @Override
    public UserVo logonAuto(String text) {
        String textNew = UUID.randomUUID().toString();
        UserVo user = (UserVo) redisTemplate.opsForValue().get(text);
        if(user == null) {
            return null;
        }
        redisTemplate.delete(text);
        redisTemplate.opsForValue().set(textNew, user);
        redisTemplate.expire(textNew, Duration.ofDays(3));
        user.setCiphertext(textNew);
        return user;
    }

    @Override
    public UserVo logonByEmail(String email, Integer check) {
        if(redisTemplate.opsForValue().get(email) == null || String.valueOf(check).compareTo((String) redisTemplate.opsForValue().get(email)) != 0) {
            return new UserVo(new User("10004", null));
        }
        User user = userMapper.selectUserByEmail(email);
        if(user == null) {
            return new UserVo(new User("10006", null));
        }
        redisTemplate.opsForValue().set(email, user);
        redisTemplate.expire(email, Duration.ofDays(3));
        String textNew = UUID.randomUUID().toString();
        UserVo userVo = new UserVo(user);
        userVo.setCiphertext(textNew);
        redisTemplate.opsForValue().set(textNew, userVo);
        redisTemplate.expire(textNew, Duration.ofDays(3));
        return userVo;
    }

    @Override
    public void updateName(String account, String name) {
        User user1 = userMapper.selectUserByAccount(account);
        user1.setUsername(name);
        userMapper.updateUserByUid(user1);
        redisTemplate.opsForValue().set(account, user1);
        new UserVo(user1);
    }

    @Override
    public UserVo updateAvatar(String account, String avatar) {
        User user1 = userMapper.selectUserByAccount(account);
        user1.setAvatar(avatar);
        userMapper.updateUserByUid(user1);
        redisTemplate.opsForValue().set(account, user1);
        return new UserVo(user1);
    }

    @Override
    public void updatePwd(String account, String password) {
        User user1 = userMapper.selectUserByAccount(account);
        user1.setPassword(password);
        userMapper.updateUserByUid(user1);
        redisTemplate.opsForValue().set(account, user1);

        new UserVo(user1);
    }

    @Override
    public void deleteUserByAccount(String account) {
        userMapper.deleteUserByAccount(account);
        redisTemplate.delete(account);
    }

    @Override
    public String sendEmail(String email) {
        String user = null, password = null;
        if(email.contains("qq.com")) {
            // 发件人称号，同邮箱地址※
            user = "1965542210@qq.com";
            // 授权码，开启SMTP时显示※
            password = "dizeskjeyuyqhccg";
        } else if(email.contains("163.com")) {
            // 发件人称号，同邮箱地址※
            user = "D3534943021@163.com";
            // 授权码，开启SMTP时显示※
            password = "OEFCLGALWRVTSHTU";
        }


        String text = String.valueOf(ThreadLocalRandom.current().nextInt(100000, 1000000));
        try {
            final Properties props = new Properties();
            props.put("mail.smtp.auth", "true");
            props.put("mail.smtp.port", "465");
            props.put("mail.smtp.ssl.enable", "true");

            if(email.contains("qq.com")) {
                props.put("mail.smtp.host", "smtp.qq.com");
            }else if(email.contains("163.com")) {
                props.put("mail.smtp.host", "smtp.163.com");
            }

            // 发件人的账号
            props.put("mail.user", user);
            //发件人的密码
            props.put("mail.password", password);

            // 构建授权信息，用于进行SMTP进行身份验证
            Authenticator authenticator = new Authenticator() {
                @Override
                protected PasswordAuthentication getPasswordAuthentication() {
                    // 用户名、密码
                    String userName = props.getProperty("mail.user");
                    String password = props.getProperty("mail.password");
                    return new PasswordAuthentication(userName, password);
                }
            };
            // 使用环境属性和授权信息，创建邮件会话
            Session mailSession = Session.getInstance(props, authenticator);
            // 创建邮件消息
            MimeMessage message = new MimeMessage(mailSession);
            // 设置发件人
            String username = props.getProperty("mail.user");
            InternetAddress form = new InternetAddress(username);
            message.setFrom(form);

            // 设置收件人
            InternetAddress toAddress = new InternetAddress(email);
            message.setRecipient(Message.RecipientType.TO, toAddress);

            // 设置邮件标题
            message.setSubject("验证码");

            // 设置邮件的内容体
            message.setContent(text, "text/html;charset=UTF-8");
            // 发送邮件
            Transport.send(message);
            redisTemplate.opsForValue().set(email, text);
            redisTemplate.expire(email, Duration.ofMinutes(5));
            return text;
        }catch (Exception e){
            e.printStackTrace();
        }
        return "error";
    }

}
